<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Use correct character set. -->
    <meta charset="utf-8" />
    <!-- Tell IE to use the latest, best version. -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <!-- Make the application on mobile take up the full browser screen and disable user scaling. -->
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"
    />
    <title>图文标注</title>
    <link href="https://cdn.jsdelivr.net/npm/cesium@1.85.0/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/cesium@1.85.0/Build/Cesium/Cesium.js"></script>
    <style>
      html,
      body,
      #cesiumContainer {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
        overflow: hidden;
      }
      #infobox {
        position: absolute;
        top: 20px;
        left: 30px;
        font-size: 14px;
        z-index: 99;
        padding: 10px 20px;
        background-color: white;
        border: 1px solid #cccccc;
      }
      .toolbox {
        position: absolute;
        top: 49%;
        left: 30px;
        z-index: 99;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
      }
      .tool-item {
        background-color: #303336;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <img id="img" style="display: none;" src="../SampleData/cover.jpg" alt="" />
    <div id="infobox"></div>
    <div class="toolbox">
      <button id="zoomIn" class="tool-item">
        <img class="tool-image" src="../SampleData/zoomIn.png" alt="" />
      </button>
      <button id="zoomOut" class="tool-item">
        <img class="tool-image" src="../SampleData/zoomOut.png" alt="" />
      </button>
    </div>
    <div id="cesiumContainer"></div>
  </body>
  <script>
    var viewer = new Cesium.Viewer('cesiumContainer', {
      imageryProvider: new Cesium.UrlTemplateImageryProvider({
        url: 'http://mt1.google.cn/maps/vt?lyrs=s&x={x}&y={y}&z={z}',
        credit: '',
        tilingScheme: new Cesium.WebMercatorTilingScheme(),
      }),
      shouldAnimate: true,
      timeline: false,
      animation: false,
    });
    viewer._cesiumWidget._creditContainer.style.display = 'none'; // 隐藏版权
    viewer.scene.globe.show = true;
    viewer.scene.debugShowFramesPerSecond = true;

    // var tilesets = new Cesium.Cesium3DTileset({
    //   url: './SampleData/Cesium3DTiles/Tilesets/Tileset/tileset.json',
    //   skipLevelOfDetail: true,
    //   maximumMemoryUsage: 1500,
    //   maximumScreenSpaceError: 16,
    //   // cullRequestsWhileMovingMultiplier: 100,
    //   dynamicScreenSpaceError: false,
    //   preferLeaves: true,
    //   debugShowContentBoundingVolume: false,
    //   debugShowViewerRequestVolume: false,
    //   debugShowBoundingVolume: false,
    // });
    // tilesets.readyPromise
    //   .then(function (tileset) {
    //     viewer.scene.primitives.add(tileset);
    //     viewer.flyTo(tileset);
    //   })
    //   .otherwise(function (error) {
    //     console.log(error);
    //   });

    var point = viewer.entities.add({
      position: Cesium.Cartesian3.fromDegrees(-75.61, 40.043, 100),
      billboard: {
        image: drawCanvas(
          '../SampleData/cover.jpg',
          'Hello World 你好 Cesium!',
          2
        ),
        // image: './SampleData/bg.png',
        sizeInMeters: true,
        scale: 0.5,
        // height: 80,
        // width: 100,
      },
    });

    viewer.flyTo(point);
    //根据图片和文字绘制canvas  ratio参数 是放大倍数
    function drawCanvas(img, text, ratio) {
      // width height

      var canvas = document.createElement('canvas'); //创建canvas标签
      var ctx = canvas.getContext('2d');
      var width = ctx.measureText(text).width + 8,
        height = 20; //高度我这里是定死的，可以作为参数参入

      canvas.style.opacity = 1;
      canvas.width = width * ratio;
      canvas.height = height * ratio;
      canvas.style.width = width + 'px';
      canvas.style.height = height + 'px';
      //然后将画布缩放，将图像放大ratio倍画到画布上 目的 是图片文字更加清晰
      ctx.scale(ratio, ratio);
      var image = new Image();
      image.src = img;
      // 图片创建是异步操作，需要在图片完成之后，再写入文字，能保证文字在图片上方。
      // 如果不在里面，会出现图片覆盖文字
      image.onload = function () {
        console.log();
        ctx.fillStyle = '#ffff00';

        ctx.drawImage(image, 0, 0, width, height);
        // 名称文字
        ctx.fillText(text, 8, height / 2 + 2);
      };
      return canvas;
    }

    // 放大缩小
    document.getElementById('zoomIn').onclick = function () {
      // 获取当前镜头位置的笛卡尔坐标
      let cameraPos = viewer.camera.position;
      // 获取当前坐标系标准
      let ellipsoid = viewer.scene.globe.ellipsoid;

      // 根据坐标系标准，将笛卡尔坐标转换为地理坐标
      let cartographic = ellipsoid.cartesianToCartographic(cameraPos);
      // 获取镜头的高度
      let height = cartographic.height;
      // if (height < 40) {
      //   return
      // }
      // 镜头拉近
      viewer.camera.zoomIn(height / 3);
    };

    document.getElementById('zoomOut').onclick = function () {
      // 获取当前镜头位置的笛卡尔坐标
      let cameraPos = viewer.camera.position;
      // 获取当前坐标系标准
      let ellipsoid = viewer.scene.globe.ellipsoid;

      // 根据坐标系标准，将笛卡尔坐标转换为地理坐标
      let cartographic = ellipsoid.cartesianToCartographic(cameraPos);
      // 获取镜头的高度
      let height = cartographic.height;
      // if (height < 40) {
      //   return
      // }
      // 镜头拉近
      viewer.camera.zoomOut(height * 1.2);
    };
    //经纬度显示
    viewer.screenSpaceEventHandler.setInputAction(function (event) {
      var earthPosition = viewer.camera.pickEllipsoid(
        event.position,
        viewer.scene.globe.ellipsoid
      );
      var cartographic = Cesium.Cartographic.fromCartesian(
        earthPosition,
        viewer.scene.globe.ellipsoid,
        new Cesium.Cartographic()
      );
      var lat = Cesium.Math.toDegrees(cartographic.latitude);
      var lng = Cesium.Math.toDegrees(cartographic.longitude);
      var height = viewer.camera.positionCartographic.height;
      document.getElementById('infobox').innerHTML =
        '<span>经度：' +
        lng.toFixed(3) +
        '</span>' +
        '<span>  纬度：' +
        lat.toFixed(3) +
        '</span>' +
        '<span>  相机高度：' +
        height +
        '</span>';
      console.log(lat, lng, height);
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  </script>
</html>
